import pyaudio, wave, NMEA, serial



# Serial port and baud rate must match that of GPS unit.
ser = serial.Serial('/dev/cu.KeySerial1', 4800, timeout=1)

# The name of the directory that contains the audio files.
mediaDirectory = 'audio'



def play(filename):
  """
  Plays a given audio file.
  """

  global mediaDirectory

  chunk = 1024
  wf = wave.open(mediaDirectory + '/' + filename, 'rb')
  p = pyaudio.PyAudio()
  # Open stream to file.
  stream = p.open(format =
                  p.get_format_from_width(wf.getsampwidth()),
                  channels = wf.getnchannels(),
                  rate = wf.getframerate(),
                  output = True)

  # Read data in advance of playback.
  data = wf.readframes(chunk)

  # Play stream.
  while data != '':
      stream.write(data)
      data = wf.readframes(chunk)

  stream.close()
  p.terminate()



def getLocation():
  """
  Reads the current latitude and longitude values.
  """

  lat,lon = 0,0
  # Coverage can be flaky, se we need to keep trying for a response,
  # and avoid throwing an exception if the returned value is bad.
  while lat == 0 and lon == 0:
    line = ser.readline()
    try:
      nmea = NMEA.NMEA()
      nmea.handle_line(line[:-1])
      lat = nmea.lat
      lon = nmea.lon
    except:
      pass
  return lat,lon
